﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;
using Newtonsoft.Json;

namespace GWEB.WebFrame.Customer
{
    public class FollowupController : PageInfoBase
    {
        String cid = "";

        [ActionFilter(IsLogin = true)]
        public ActionResult Index(String id,String Ids, String KeyCodes)
        {
            if (!Fun.IDVerify(Ids, KeyCodes))
                return Content(WebMessage.NoGrant);
            cid = Ids;            
            String keyCode = "";
            ViewBag.Ids = Ids;
            ViewBag.KeyCodes = KeyCodes;
            ViewBag.Guid = Guid.NewGuid().ToString("N");
            return Load("Followup", "Customer/Followup", id, keyCode);
        }
        protected override void FieldAddInit(DataRow data)
        {
            data["cid"] = cid;
            base.FieldAddInit(data);
        }
        protected override string Validate(Dictionary<string, object> data)
        {
            String cusgrade = Fun.cString(data["Cusgrade"]);
            String couTeachId= Fun.cString(data["CouTeachId"]);
            if (!(cusgrade == "0" || cusgrade == "9"))
                data["IsAuditions"] = 0;//只有预约到访 和已到访有试听功能
            if (data["IsAuditions"].ToString() == "1" && couTeachId == "0")
            {
                return "请选择试听课程";
            }
            if (int.Parse(couTeachId) >0) {

                String courseId=BasePage.bd.ExecuteScalarString("select courseId from cu_TeacherCourse where id="+couTeachId);
                data.Add("CourseId", courseId);
            }

            String cid = Fun.cString(data["cid"]);
            String date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            String sql = String.Format("select top 1 AdviserId,ReceiveDate,LeagueId From cu_Cus_Distribution where cid={0} and state=1 order by id desc", cid);
            DataRow dr = BasePage.bd.ExecuteRow(sql);
            if (dr == null) return "该客户没有分配记录";

            data.Add("AdviserId", dr["AdviserId"]);
            data.Add("ReceiveDate", dr["ReceiveDate"]);
            data.Add("LeagueId", dr["LeagueId"]);
            data.Add("CreateDate", date);
            data.Add("CourseState", 0);

            data.Add("AccountCount", 0);
            data.Add("ContractCount", 0);
            String guid = data["guid"].ToString();
            if (((cusgrade == "0" || cusgrade == "9") && data["isCharge"].ToString() == "1") || cusgrade == "6" )
            {
                int count = BasePage.bd.ExecuteScalarInt(String.Format("select count(*) from cu_Account where guid='{0}'", guid));
                if (count == 0)
                {
                    return "填写付费明细";
                }
                data["AccountCount"] = count;
            }
            if (cusgrade == "7")
            {
                int count = BasePage.bd.ExecuteScalarInt(String.Format("select count(*) from cu_contract where guid='{0}'", guid));
                if (count == 0)
                {
                    return "请先签订合同";
                }
                data["ContractCount"] = count;
            }
            return base.Validate(data);
        }
        protected override SqlState SqlExecute(BaseData bd, String id, Dictionary<String, Object> data)
        {
            String date =  data["CreateDate"].ToString();
            String cid = Fun.cString(data["cid"]);
            String userId = BasePage.GetUserId(Session);           
            Dict dict = BasePage.getDict(Session);
            String cusgrade = Fun.cString(data["Cusgrade"]);
            String makeDate = Fun.cString(data["MakeDate"]);           
            String nextMakeDate = "";
            String arriveDate = "";
            String custArrive = "";
            String guid = data["guid"].ToString();data.Remove("guid");
            int accountCount = int.Parse(data["AccountCount"].ToString());data.Remove("AccountCount");
            int contractCount = int.Parse(data["ContractCount"].ToString());data.Remove("ContractCount");

            if (makeDate != "")
            {
                DataRow[] drs = dict.dt.Select("typeid='D05' and did='" + cusgrade + "'");
                if (drs.Length == 1)
                {
                    String day = Fun.cString(drs[0]["helpcode"]);
                    //ABC类提醒
                    if (day != "")
                    {
                        nextMakeDate = Convert.ToDateTime(makeDate).AddDays(double.Parse(day)).ToString("yyyy-MM-dd");
                        data.Add("nextMakeDate", nextMakeDate);
                    }
                }
            }
            //依据resultId，修改主表状态
            //0，新增未分配，1，已分配未领取，2、已领取未跟进，3，已跟进，4已到访，5已交定金，6，已签合同,7历史客户，8淘汰 9已到访 90提醒
            String custState = "custState";
            if (cusgrade == "0")
            {
                //预约
                custState = "4";
                nextMakeDate = makeDate;
                data["nextMakeDate"]= nextMakeDate;
            }
            if (cusgrade == "8")
            { nextMakeDate = makeDate; custState = "3"; data["nextMakeDate"]=nextMakeDate; }
            else if (cusgrade == "1" || cusgrade == "2" || cusgrade == "3")//ABC
            {
                custState = "3";

            }
            else if (cusgrade == "4")//历史
                custState = "7";
            else if (cusgrade == "5")//淘汰
                custState = "8";
            else if (cusgrade == "6")//交定金
            { custState = "5"; nextMakeDate = makeDate; data["nextMakeDate"]= nextMakeDate; }
            // else if (cusgrade == "7")//合同
            //    custState = "6";
            else if (cusgrade == "9")
            {//已到访
                custState = "3";
                custArrive = "1";
                arriveDate = makeDate;
            }
            
            String set = "";
            if (arriveDate != "") set += String.Format(",arriveDate='{0}'", arriveDate);
            if (custArrive != "") set += String.Format(",custArrive='{0}'", custArrive);
            if (nextMakeDate != "")
                set += String.Format(",nextMakeDate='{0}'", nextMakeDate);
            else
                set += String.Format(",nextMakeDate=null");

            // else if (resultId == "7")//签合同
            //     custState = "6";

            String[] sqls = new string[5];
            int excuteCount = 2;
           
            sqls[1] = String.Format("update cu_Customers set custState={0},LatelyFoupDate='{1}',cusgrade='{2}'{3} where id={4}",
                custState, date, cusgrade,set,cid);
            //有预约插入到签到表
            if (data["IsAuditions"].ToString() == "1") {               
                excuteCount++;
                sqls[2] = String.Format(@"insert into cu_TeacherCourse_Sign
(
    Cid,Godate,Tid,Pnumber,SignupClass,CreateId,Createdate,
    state,IsAuditions,FollowUpId,AchievementId,AchievementName,LeagueId
)
select t3.id,t1.TeachDate,t1.id,1,0,{3},'{4}',
    0,'P',[id],LatelyReceId,t4.sshowname,t3.LeagueId              
from cu_TeacherCourse t1
inner join cu_course t2 on t1.CourseId=t2.id
inner join cu_Customers t3 on t2.LeagueId=t3.LeagueId and datediff(mm,t3.BirdDate,getdate()) between t2.startMonth and t2.EndMonth
inner join tb_sys_users t4 on LatelyReceId=t4.iuserid
where t1.TeachDate='{1}' and convert(varchar(10),getdate(),120)<=t1.TeachDate and t3.id={0} and t1.id={2}
and StudentNumber>(select count(*) from cu_TeacherCourse_Sign where Tid=t1.id)
and not exists(select * from cu_TeacherCourse_Sign where Tid=t1.id and cid={0})", cid, makeDate, data["CouTeachId"], userId,date);
            }
            //更新收费与合同表
            if (accountCount > 0)
            {
                excuteCount += accountCount;
                sqls[3] = String.Format("update cu_Account set FollowupId=[id] where guid='{0}'", guid);
                data["ChargeId"] = guid;
            }
            else
                data["IsCharge"] = "0";
            if (contractCount > 0)
            {
                excuteCount += contractCount;
                sqls[4] = String.Format("update cu_contract set FollowupId=[id] where guid='{0}'", guid);
            }
            sqls[0] = BaseData.MapToSql("cu_Cus_followup", "id", id, data);
            bool t = bd.ExecuteSQL(sqls, excuteCount, "cu_TeacherCourse_Sign","id",id);
            return t ? SqlState.True : SqlState.False;
        }

        [ActionFilter(IsJson = true)]
        public JsonResult Course(String Ids, String KeyCodes, String date)
        {
            if (!Fun.IDVerify(Ids, KeyCodes))
                return BasePage.Json(ResultData.Error(WebMessage.NoGrant));
            //客户所在加盟商的课程，月龄及时间不超过相应限制，及还有课程
            //StudentNumber > count(cu_TeacherCourse_Sign)
            //预约时间 = TeachDate 当前时间<=排课时间
            //宝宝月龄 >= StartMonth and 宝宝月龄<= EndMonth
            String sql = String.Format(@"select t1.id,t2.CourseName 
from cu_TeacherCourse t1
inner join cu_course t2 on t1.CourseId=t2.id
inner join cu_Customers t3 on t2.LeagueId=t3.LeagueId and datediff(mm,t3.BirdDate,getdate()) between t2.startMonth and t2.EndMonth
where t1.TeachDate='{1}' and  convert(varchar(10),getdate(),120)<=t1.TeachDate and t3.id={0}
and StudentNumber>(select count(*) from cu_TeacherCourse_Sign where Tid=t1.id)
and not exists(select * from cu_TeacherCourse_Sign where Tid=t1.id and cid={0})", Ids, date);
            return BasePage.Json(ResultData.OK(BasePage.bd.ExecuteDictArray(sql)));          
        }
    }
}